<template>
  <div class="login-wrapper">
    <div class="login-container">
      <div class="login-title">登 录</div>
      
      <el-form :model="user" :rules="rules" ref="formRef" class="login-form">
        <el-form-item prop="username">
          <el-input 
            placeholder="用户名" 
            prefix-icon="el-icon-user" 
            v-model="user.username"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input 
            placeholder="密码" 
            prefix-icon="el-icon-lock" 
            show-password 
            v-model="user.password"
          />
        </el-form-item>
        
        <!-- 验证码组件 -->
        <el-form-item prop="verifyCode">
          <div class="verify-code-container">
            <el-input 
              placeholder="验证码" 
              v-model="user.verifyCode" 
              @keyup.enter="handleLogin"
            />
            <ValidCode @update:code="handleValidCode" />
          </div>
        </el-form-item>
        
        <div class="btn-group">
          <el-button type="primary" @click="handleLogin">登录</el-button>
          <el-button type="text" @click="$router.push('/register')">注册</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import request from '@/utils/request';
import ValidCode from '@/components/ValidCode.vue';

// 路由实例
const router = useRouter();

// 表单引用
const formRef = ref(null);

// 表单数据
const user = reactive({
  username: '',
  password: '',
  verifyCode: ''
});

// 验证码存储
const validCode = ref('');

// 表单验证规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  verifyCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '验证码为4位字符', trigger: 'blur' }
  ]
});

// // 生命周期钩子
// onMounted(() => {
//   // 检查本地存储的用户信息
//   const userInfo = localStorage.getItem('user');
//   if (userInfo) {
//     router.push('/table');
//   }
// });

// 处理验证码生成
const handleValidCode = (code) => {
  console.log('接收到的验证码:', code); // 检查是否有值
  validCode.value = code;
};

// 登录处理函数
const handleLogin = () => {
  formRef.value.validate((valid) => {
    if (!valid) return;
    
    // 验证验证码
    if (user.verifyCode.toUpperCase() !== validCode.value.toUpperCase()) {
      console.log(user.verifyCode)
      console.log("yanzhnegma "+validCode.value)
      ElMessage.error('验证码错误');
      return;
    }
    
    // 发送登录请求
    request.get('/login', {
      params: {
        name: user.username,
        password: user.password
      }
    }).then(res => {
      if (res.success) {
        // 根据用户角色存储信息并跳转
        const userName = res.content.name;
        
        if (userName === 'admin') {
          localStorage.setItem('user_admin', JSON.stringify(userName));
          router.push('/P_pork');
        } else if (userName === 'machine') {
          localStorage.setItem('user_machine', JSON.stringify(userName));
          router.push('/machine');
        } else {
          localStorage.setItem('user', JSON.stringify(userName));
          router.push('/table');
        }
      } else {
        ElMessage.error('用户名或密码错误');
      }
    }).catch(() => {
      ElMessage.error('登录请求失败');
    });
  });
};

// 监听用户输入，清空错误提示
watch(() => user.verifyCode, () => {
  if (formRef.value) {
    formRef.value.clearValidate('verifyCode');
  }
});
</script>

<style scoped>
.login-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
   background-image: url('@/assets/bg/bg11.png'); /* 假设背景图片在assets目录下 */
  background-size: cover;
  background-position: center;
}

.login-container {
  width: 360px;
  padding: 30px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 30px;
  color: #303133;
}

.login-form .el-form-item {
  margin-bottom: 20px;
}

.verify-code-container {
  display: flex;
  gap: 10px;
}

.btn-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}
</style>